package cn.hnu.qq.server.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import cn.hnu.qq.entity.Crowd;
import cn.hnu.qq.entity.User;
import cn.hnu.qq.server.dao.CrowdDao;
import cn.hnu.qq.server.dao.UserDao;

@Transactional
public class CrowdDaoImpl implements CrowdDao{

	@PersistenceContext
	private EntityManager manager;
	
	private UserDao userDao;
	
	public Crowd findById(Integer Id) {
		return manager.find(Crowd.class, Id);
	}

	public Crowd findByName(String groupName) {
		String jpql = "SELECT g FROM Crowd g WHERE g.crowdName = :groupName";
		Query query = manager.createQuery(jpql);
		query.setParameter("groupName", groupName);
		List<Crowd> crowds = query.getResultList();
		return crowds.size() > 0 ? crowds.get(0) : null;
	}

	public Boolean isExist(String name) {
		if(findByName(name) != null){
			return true;
		}
		return false;
	}

	public Boolean isExist(Integer id) { 
		if(findById(id) != null){
			return true;
		}
		return false;
	}

	public EntityManager getManager() {
		return manager;
	}

	public void setManager(EntityManager manager) {
		this.manager = manager;
	}

	public void persist(Crowd group) {
		manager.persist(group);
	}

	public void merge(Crowd group) {
		manager.merge(group);
	}

	public int joinCrowd(String user, String crowd) {
		Crowd _crowd = findByName(crowd);
		User _user = userDao.findByAcount(user);
		if(_crowd == null || _user == null){
			return -1;
		}
		if(_crowd.getUsers().contains(_user)){
			return 1;
		}
		_crowd.addUser(_user);
		manager.merge(_crowd);
		return 0;
	}

	public boolean isAlreadyInCrowd(String user,String crowd) {
		User _user = userDao.findByAcount(user);
		
		if(_user == null) return false;
		
		Crowd _crowd = findByName(crowd);
		
		if(_crowd == null) return false;
		
		return _crowd.getUsers().contains(_user);
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void exitCrowd(String crowd, String user) {
		Crowd _crowd = findByName(crowd);
		User _user = userDao.findByAcount(user);
		_crowd.removeUser(_user);
		manager.merge(_crowd);
	}
	
	
}
